// 博客分类管理API服务
const express = require('express');
const BlogCategory = require('../models/BlogCategory');
const { authenticateToken, Authorization } = require('../security');
const { USER_ROLES } = require('../security');
const { cacheMiddleware, clearCache } = require('../cache');

const router = express.Router();

// 获取所有分类
router.get('/blog-categories', cacheMiddleware(300), async (req, res) => {
    try {
        const page = parseInt(req.query.page) || 1;
        const limit = parseInt(req.query.limit) || 100;
        
        const result = await BlogCategory.findAll({ page, limit });
        
        res.json({
            success: true,
            data: {
                categories: result.categories,
                total: result.total,
                page: page,
                limit: limit,
                totalPages: result.totalPages
            }
        });
    } catch (error) {
        console.error('获取分类列表失败:', error);
        res.status(500).json({
            success: false,
            message: '获取分类列表失败'
        });
    }
});

// 获取分类树
router.get('/blog-categories/tree', cacheMiddleware(600), async (req, res) => {
    try {
        const categoryTree = await BlogCategory.getCategoryTree();
        
        res.json({
            success: true,
            data: categoryTree
        });
    } catch (error) {
        console.error('获取分类树失败:', error);
        res.status(500).json({
            success: false,
            message: '获取分类树失败'
        });
    }
});

// 获取单个分类
router.get('/blog-categories/:id', cacheMiddleware(600), async (req, res) => {
    try {
        const category = await BlogCategory.findById(parseInt(req.params.id));
        
        if (!category) {
            return res.status(404).json({
                success: false,
                message: '分类不存在'
            });
        }
        
        res.json({
            success: true,
            data: category
        });
    } catch (error) {
        console.error('获取分类失败:', error);
        res.status(500).json({
            success: false,
            message: '获取分类失败'
        });
    }
});

// 创建分类
router.post('/blog-categories', authenticateToken, Authorization.requirePermission('blog_categories', 'create'), async (req, res) => {
    try {
        const { name, slug, description, parentId, sortOrder } = req.body;
        
        if (!name) {
            return res.status(400).json({
                success: false,
                message: '分类名称不能为空'
            });
        }
        
        // 检查分类名称是否已存在
        const existingCategory = await BlogCategory.findAll();
        const nameExists = existingCategory.categories.some(cat => cat.name === name);
        
        if (nameExists) {
            return res.status(400).json({
                success: false,
                message: '分类名称已存在'
            });
        }
        
        const category = await BlogCategory.create({
            name,
            slug,
            description,
            parentId,
            sortOrder
        });
        
        // 清除缓存
        clearCache('/api/blog-categories');
        clearCache('/api/blog-categories/tree');
        
        res.status(201).json({
            success: true,
            message: '分类创建成功',
            data: category
        });
    } catch (error) {
        console.error('创建分类失败:', error);
        res.status(500).json({
            success: false,
            message: '创建分类失败'
        });
    }
});

// 更新分类
router.put('/blog-categories/:id', authenticateToken, Authorization.requirePermission('blog_categories', 'update'), async (req, res) => {
    try {
        const category = await BlogCategory.findById(parseInt(req.params.id));
        
        if (!category) {
            return res.status(404).json({
                success: false,
                message: '分类不存在'
            });
        }
        
        // 检查分类名称是否已存在（排除当前分类）
        if (req.body.name) {
            const existingCategory = await BlogCategory.findAll();
            const nameExists = existingCategory.categories.some(
                cat => cat.name === req.body.name && cat.id !== category.id
            );
            
            if (nameExists) {
                return res.status(400).json({
                    success: false,
                    message: '分类名称已存在'
                });
            }
        }
        
        await category.update(req.body);
        
        // 清除缓存
        clearCache('/api/blog-categories');
        clearCache('/api/blog-categories/tree');
        clearCache(`/api/blog-categories/${category.id}`);
        
        res.json({
            success: true,
            message: '分类更新成功',
            data: category
        });
    } catch (error) {
        console.error('更新分类失败:', error);
        res.status(500).json({
            success: false,
            message: '更新分类失败'
        });
    }
});

// 删除分类
router.delete('/blog-categories/:id', authenticateToken, Authorization.requirePermission('blog_categories', 'delete'), async (req, res) => {
    try {
        const category = await BlogCategory.findById(parseInt(req.params.id));
        
        if (!category) {
            return res.status(404).json({
                success: false,
                message: '分类不存在'
            });
        }
        
        await category.delete();
        
        // 清除缓存
        clearCache('/api/blog-categories');
        clearCache('/api/blog-categories/tree');
        clearCache(`/api/blog-categories/${category.id}`);
        
        res.json({
            success: true,
            message: '分类删除成功'
        });
    } catch (error) {
        console.error('删除分类失败:', error);
        res.status(500).json({
            success: false,
            message: error.message || '删除分类失败'
        });
    }
});

// 获取分类统计
router.get('/blog-categories/:id/stats', cacheMiddleware(300), async (req, res) => {
    try {
        const categoryId = parseInt(req.params.id);
        const category = await BlogCategory.findById(categoryId);
        
        if (!category) {
            return res.status(404).json({
                success: false,
                message: '分类不存在'
            });
        }
        
        const stats = await BlogCategory.getStats(categoryId);
        
        res.json({
            success: true,
            data: stats
        });
    } catch (error) {
        console.error('获取分类统计失败:', error);
        res.status(500).json({
            success: false,
            message: '获取分类统计失败'
        });
    }
});

module.exports = router;